import { API, rootPath } from "../../utils/const";
Component({
    properties: {
      notifications: {
        type: Array,
        value: []
      },
    },
    
    methods: {
      onNotificationClick(e) {
        const notification = e.currentTarget.dataset.item;
        console.log(notification);
        let navigateTo = this.getJumpPath(notification);

        let updatedNotifications = this.data.notifications;
        updatedNotifications.forEach(item => {
            if(item.id === notification.id){
                item.isNotificationVisible = false;
            }});
        console.log(updatedNotifications)
        // Mark as read
        this.markAsRead(notification);
        this.setData({ notifications: updatedNotifications });
        // Navigate to the detail page (adjust the path as needed)
        wx.navigateTo({
            url: navigateTo
            });
      },
      
      onCancelClick(e) {
        const notification = e.currentTarget.dataset.item;
        // e.stopPropagation(); // Prevent triggering the parent click event
  
        // Remove the notification from UI

        let updatedNotifications = this.data.notifications;
        updatedNotifications.forEach(item => {
            if(item.id === notification.id){
                item.isNotificationVisible = false;
            }});
        console.log(updatedNotifications)
        // Mark as read
        this.markAsRead(notification);
        this.setData({ notifications: updatedNotifications });
      },
  
      markAsRead(notification) {
        const that = this;
        const url = rootPath + API.markNotificationAsRead;
        const key = `${notification.targetIdentityId}-${notification.type}`;
        let needUpdateNotificateIds = [];
        that.data.notifications.forEach(noti => {
            let tmpKey = `${noti.targetIdentityId}-${noti.type}`;
            if (tmpKey === key){
                needUpdateNotificateIds.push(noti.id);
            }
        })
        
        console.log(needUpdateNotificateIds);
        let header = {};
        let token = wx.getStorageSync('token');
        let userId = wx.getStorageSync('LoginId');
        let userRole = wx.getStorageSync('loginType');
        header['authorization'] = "Bearer " + token;
        needUpdateNotificateIds.forEach(notificationId => {
            console.log(`Calling ${url}  with ${userRole} - ${userId} ... `); 
            console.log(`Marking ${notificationId} to read...`);
            wx.request({
            url: `${url}?notificationId=${notificationId}`,
            header: header,
            method: 'POST',
            success(res) {
                console.log('Notification marked as read:', res);
            },
            fail(err) {
                console.error('Failed to mark notification as read:', err);
            }
            });})
      },

      getJumpPath(notification){
        if(notification.type === 'ChatMessage'){
            return `/pages/chatPage/chatpage?id=${notification.targetId}&name=${notification.targetName}&role=${notification.targetRole}`
        }
        else if (notification.type === 'RiskPatientInfo'){
            return '/pages/doctorview/doctorview'
        }
        else if (notification.type === 'AgreementLetter') {
            return '/pages/getAgreementLetters/getAgreementLetters'
        }
        else if (notification.type === 'PostOperationMaterial') {
          return '/pages/getMaterials/getMaterials'
        }
        else if (notification.type === 'HandleComplaint') {
          return '/pages/complaintList/complaintList'
        }
      }
    }
  });
  